package com.wzx.ptplatform.service.impl;

import com.wzx.ptplatform.dao.CityDao;
import com.wzx.ptplatform.domain.City;
import com.wzx.ptplatform.domain.Province;
import com.wzx.ptplatform.service.CityService;
import com.wzx.ptplatform.utils.PtplatformException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * @author 紫煦桉
 */
@Service
public class CityServiceImpl implements CityService {

    @Resource
    private CityDao cityDao;

    @Override
    public List<City> findAll() throws PtplatformException {
        return cityDao.findAll();
    }

    @Override
    public Page<City> findList(City city, Integer page, Integer limit) throws PtplatformException {
        Specification<City> spec = (Specification<City>) (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            List<Expression<Boolean>> exList = predicate.getExpressions();//动态SQL表达式集合
            if (city.getCityName() != null) {
                exList.add(criteriaBuilder.like(root.get("cityName").as(String.class), "%" + city.getCityName() + "%"));
            }
            if (city.getProvince() != null && city.getProvince().getId() != null) {
                exList.add(criteriaBuilder.equal(root.get("province").get("id").as(Long.class), city.getProvince().getId()));
            }
            return predicate;
        };
        PageRequest pageable = PageRequest.of(page, limit, Sort.Direction.DESC, "id");
        return cityDao.findAll(spec, pageable);
    }

    @Override
    public City findById(long id) throws PtplatformException {
        return cityDao.findById(id).orElse(null);
    }

    @Override
    public boolean saveOrEdit(City city) throws PtplatformException {
        try {
            cityDao.saveAndFlush(city);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteById(long id) throws PtplatformException {
        try {
            cityDao.deleteById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
